package com.cction.comm;

import android.content.Context;

import com.cction.entry.CctionBean;
import com.cction.entry.SaveCompoundDataBean;
import com.google.gson.Gson;

import java.util.ArrayList;

/**
 * 数据保存
 */

public class SaveCompoundUtils {
    public static final String DATAKEY = "new_datakey";
    public static SaveCompoundDataBean saveCompoundDataBean;

    /**
     * 初始化
     *
     * @return
     */
    public static SaveCompoundDataBean init() {
        SaveCompoundDataBean saveCompoundDataBean = new SaveCompoundDataBean();
        ArrayList<CctionBean> arrayList = new ArrayList<>();
        saveCompoundDataBean.arrayList = arrayList;
        return saveCompoundDataBean;
    }

    /**
     * 获取数据
     */
    public static SaveCompoundDataBean readData(Context context) {
        String value = (String) SPUtils.get(context, DATAKEY, "");
        if (value.isEmpty()) {
            return init();
        }
        saveCompoundDataBean = new Gson().fromJson(value, SaveCompoundDataBean.class);
        if (saveCompoundDataBean != null) {
            return saveCompoundDataBean;
        }
        return init();
    }

    /**
     * 写入数据
     */
    public static void wirteData(Context context, CctionBean cctionBean) {
        if (saveCompoundDataBean == null) {
            saveCompoundDataBean = readData(context);
        }
        saveCompoundDataBean.arrayList.add(cctionBean);
        String value = new Gson().toJson(saveCompoundDataBean);
        SPUtils.put(context, DATAKEY, value);
    }

    /**
     * 删除
     */
    public static void remove(Context context, CctionBean cctionBean) {
        if (saveCompoundDataBean == null) {
            saveCompoundDataBean = readData(context);
        }
        int size = saveCompoundDataBean.arrayList.size();
        for (int i = 0; i < size; i++) {
            CctionBean bean = saveCompoundDataBean.arrayList.get(i);
            if (bean.id.equals(cctionBean.id)) {
                saveCompoundDataBean.arrayList.remove(i);
                break;
            }
        }
        String value = new Gson().toJson(saveCompoundDataBean);
        SPUtils.put(context, DATAKEY, value);
    }


    /**
     * 清空数据
     */
    public static void clear(Context context) {
        saveCompoundDataBean = null;
        SPUtils.put(context, DATAKEY, "");
    }
}
